package eu.vconect.orch.servlets;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import eu.vconect.orch.HangoutSession;


/**
 * Servlet implementation class Main
 */
@WebServlet("/index")
public class Main extends HttpServlet {
       
	private static final long serialVersionUID = -1564158412319777258L;
	private static Logger LOG = Logger.getLogger(Main.class);	
	private static final String JSP = "/main.jsp";	

	/**
     * @see HttpServlet#HttpServlet()
     */
    public Main() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("Main called. Forwaring the request to main.jsp...");
		
		if ( request.getParameter("command") != null && request.getParameter(ReqParams.hangoutUrl.toString()) != null ) {
			if ( request.getParameter("command").toLowerCase().startsWith("delete") ) {
				try {
					HangoutSession.reset(request.getParameter(ReqParams.hangoutUrl.toString()));
				} catch (URISyntaxException e) {
					LOG.warn("URISyntaxException: " + request.getParameter(ReqParams.hangoutUrl.toString()));
				}				
			}
		}
		
		request.setAttribute("version", "1");
		if ( !HangoutSession.instanceKeySet().isEmpty() ) {
			String[] keys = HangoutSession.instanceKeySet().toArray(new String[0]); 			
			request.setAttribute(ReqParams.hangoutUrl.toString(), keys);
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(JSP);
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
